package test.hxy.mongoSchoolSimple.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import test.hxy.mongoSchoolSimple.DTO.Response;
import test.hxy.mongoSchoolSimple.model.Book;
import test.hxy.mongoSchoolSimple.service.BookService;

import java.util.List;

@RestController
@RequestMapping("/book")
public class BookController extends BaseController {
	@Autowired
	BookService bookService;

	@GetMapping("/findAll")
	@ResponseBody
	public Response<List<Book>> findAll(){
		List<Book> books = bookService.findAll();
		if (books.size() == 0) {
			return getFailResult(404, "没找到!");
		} else {
			return getSuccessResult(books);
		}
	}

	@GetMapping("/findByBookNameContains")
	@ResponseBody
	public Response<List<Book>> findByBookNameContains(@RequestParam String bookName){
		List<Book> books = bookService.findByBookNameContains(bookName);
		if (books.size() == 0) {
			return getFailResult(404, "没找到!");
		} else {
			return getSuccessResult(books);
		}
	}

	@GetMapping("/findByisbnEquals")
	@ResponseBody
	public Response<Book> findByisbnEquals(@RequestParam String isbn){
		Book books = bookService.findByisbnEquals(isbn);
		if (books == null) {
			return getFailResult(404, "没找到!");
		} else {
			return getSuccessResult(books);
		}
	}

	@PostMapping("/insert")
	@ResponseBody
	public Response<Book> insertBook(@RequestBody Book book) {
		Book temp = bookService.insertBook(book);
		if (temp == null) {
			return getFailResult(400, "ID已存在!");
		} else {
			return getSuccessResult(temp);
		}
	}

	@GetMapping("/delete")
	@ResponseBody
	public Response<Book> delete(@RequestParam String isbn){
		Book books = bookService.delete(isbn);
		if (books == null) {
			return getFailResult(404, "没找到!");
		} else {
			return getSuccessResult(books);
		}
	}

	@PostMapping("/update")
	@ResponseBody
	public Response<String> update(@RequestBody Book book) {
		if (bookService.delete(book.getIsbn()) != null) {
			bookService.insertBook(book);
			return getSuccessResult("Success");
		} else {
			return getFailResult(404, "不存在该数据");
		}
	}

	@GetMapping("/findByTeacherId")
	@ResponseBody
	public Response<List<Book>> findByTeacherId(@RequestParam String teacherId) {
		List<Book> books = bookService.findByteacherIdEquals(teacherId);
		if (books == null) {
			return getFailResult(404, "没找到!");
		} else {
			return getSuccessResult(books);
		}
	}

	@GetMapping("/findByPublisher")
	@ResponseBody
	public Response<List<Book>> findByPublisher(@RequestParam String publisher) {
		List<Book> books = bookService.findByPublisherEquals(publisher);
		if (books == null) {
			return getFailResult(404, "没找到!");
		} else {
			return getSuccessResult(books);
		}
	}

}
